package com.weic.easycache.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.widget.ImageView;

public class CircleImageView extends ImageView {
	//private final PorterDuffXfermode mPorterDstIn = new PorterDuffXfermode(PorterDuff.Mode.DST_IN);
	//注意，很多手机不支持Mode.DST_IN
	private final PorterDuffXfermode mPorterSrcIn = new PorterDuffXfermode(PorterDuff.Mode.SRC_IN);

	private final Paint mPaint = new Paint();
	private Canvas mCanvas = new Canvas();
	private Bitmap mBitmap;

	private int mPLeft, mPTop, mPRight, mPBottom, mClipRight, mClipBottom;
	private float mCircleCenterX, mCircleCenterY, mCircleRadius;

	public CircleImageView(Context context) {
		super(context);
		init();
	}

	public CircleImageView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public CircleImageView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	private void init() {
		//mPaint.setStyle(Paint.Style.STROKE);	//暂不设置
		//设置抗锯齿，三者必须同时设置效果才可以
		mPaint.setAntiAlias(true);	//等同于mPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
		mPaint.setFilterBitmap(true);
		mPaint.setDither(true);
	}

	@Override
	protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
		super.onLayout(changed, left, top, right, bottom);
		if (mBitmap != null) {
			mBitmap.recycle();
			mBitmap = null;
		}
		mPLeft = getPaddingLeft();
		mPTop = getPaddingTop();
		mPRight = getPaddingRight();
		mPBottom = getPaddingBottom();

		mClipRight = getWidth() - mPRight;
		mClipBottom = getHeight() - mPBottom;

		int width = mClipRight - mPLeft;
		int height = mClipBottom - mPTop;
		mCircleCenterX = mPLeft + width * 1.0f / 2;
		mCircleCenterY = mPTop + height * 1.0f / 2;
		mCircleRadius = Math.min(width, height) * 1.0f / 2;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		//TODO 注意：如果是局部变量，而且方法结束后没有赋空值，则会出现图像绘制错误（绘制的是其他图像）的奇葩问题
		if (mBitmap == null) mBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
		mCanvas.setBitmap(mBitmap);
		int saveCount = mCanvas.save();
		mCanvas.setDensity(canvas.getDensity());
		mCanvas.setDrawFilter(canvas.getDrawFilter());
		super.onDraw(mCanvas);
		mCanvas.restoreToCount(saveCount);
		try { mCanvas.setBitmap(null); }catch(Exception e) {}

		saveCount = canvas.saveLayer(null, null, Canvas.ALL_SAVE_FLAG);

		canvas.clipRect(mPLeft, mPTop, mClipRight, mClipBottom);
		mPaint.setXfermode(null);
		canvas.drawCircle(mCircleCenterX, mCircleCenterY, mCircleRadius, mPaint);
		mPaint.setXfermode(mPorterSrcIn);
		canvas.drawBitmap(mBitmap, 0, 0, mPaint);

		canvas.restoreToCount(saveCount);
	}
}
